/*
 * Project Name demo
 * File Name SocketServer
 * Package Name com.huxiaosu.demo.socketio.config
 * Create Time 2023/1/28
 * Create by name：liujie
 */
package com.huxiaosu.demo.socketio.configuration;

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.huxiaosu.demo.socketio.config.SocketIoConfig;
import com.huxiaosu.demo.socketio.listener.SocketEventListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * Description
 *
 * @ClassName: SocketServer
 * @author: liujie
 * @date: 2023/1/28 14:27
 */
@Component
public class SocketServerConfiguration {
    private final SocketIoConfig socketIoConfig;
    private final SocketEventListener socketEventListener;

    @Autowired
    public SocketServerConfiguration(SocketIoConfig socketIoConfig, SocketEventListener socketEventListener) {
        this.socketIoConfig = socketIoConfig;
        this.socketEventListener = socketEventListener;
    }

    @Bean
    public SocketIOServer socketIoServer(){
        SocketConfig socketConfig = new SocketConfig();
        socketConfig.setReuseAddress(socketIoConfig.isReuseAddress());
        socketConfig.setSoLinger(0);
        socketConfig.setTcpNoDelay(socketIoConfig.isTcpNoDelay());


        Configuration config = new Configuration();
        config.setSocketConfig(socketConfig);
        config.setHostname(socketIoConfig.getHost());
        config.setPort(socketIoConfig.getPort());
        config.setAllowCustomRequests(socketIoConfig.isAllowCustomRequests());
        config.setUpgradeTimeout(socketIoConfig.getUpgradeTimeout());
        config.setPingInterval(socketIoConfig.getPingInterval());
        config.setPingTimeout(socketIoConfig.getPingTimeout());
        config.setBossThreads(socketIoConfig.getBossCount());
        config.setWorkerThreads(socketIoConfig.getWorkCount());

        SocketIOServer server = new SocketIOServer(config);
        server.addListeners(socketEventListener);
        return server;
    }
    @Bean
    public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketIoServer){
        return new SpringAnnotationScanner(socketIoServer);
    }
}